package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BLY {
    // BLY可以正常登陆和搜索

    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO BLY############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            page.navigate("http://shop.pnbly.com/");

            page.click("text=登录");
            // page.pause();
            page.click("text=账号密码登录");
            // page.waitForTimeout(1200);
            // page.click("text=账号密码登录");
            page.click("[placeholder=\"请输入账号\"]");
            page.fill("[placeholder=\"请输入账号\"]", site.getUserName());

            // Press Enter

            page.click("[placeholder=\"请输入你的密码\"]");
            // Fill input[name="password"]
            page.fill("[placeholder=\"请输入你的密码\"]", site.getPassWord());

            page.waitForNavigation(() -> {
                page.click(":nth-match(:text(\"登录\"), 4)");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO BLY#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {

        log.info("############START FETCH FROM BLY########");
        List<Result> initList = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();
            page.navigate(site.getSiteUrl());
            log.info("*****BLY SEARCH KEYWORD*****");
            log.info(search.getKeywordStr());
            String pinyin = PinyinUtil.getFirstLetter(search.getKeywordStr(), "");
            log.info(pinyin);
            log.info("*****BLY SEARCH KEYWORD*****");

            page.click(":nth-match([placeholder=\"请输入通用名 | 准字号 | 拼音码 | 厂家\"], 2)");

            // Fill [placeholder="口罩"]
            page.fill(":nth-match([placeholder=\"请输入通用名 | 准字号 | 拼音码 | 厂家\"], 2)", pinyin); // Click
                                                                                           // text=搜索

            page.waitForNavigation(() -> {
                page.click(".content div:nth-child(2) .search-box .search-container .search-btn");
            });
            page.waitForTimeout(1500);
            String content = page.innerHTML("#app");

            Document doc = Jsoup.parseBodyFragment(content);
            initList = getList(content, search, site);

            if (!page.isVisible(".btn-next")) {
                log.info("**************BLY FOUND NEW PRODUCTS!!!******************");
                log.info(Integer.toString(initList.size()));
                log.info("**************BLY FOUND NEW PRODUCTS!!!******************");
                return initList;
            }
            Element rightArrow = doc.getElementsByClass("btn-next").first();
            boolean hasNext = !StrUtil.equals("disabled", rightArrow.attributes().get("disabled"));

            // log.info("WE FETCH FROM INIT PAGE");
            page.waitForTimeout(1500);

            List<Result> otherList = new ArrayList<>();

            while (hasNext) {
                page.click(".btn-next");
                page.waitForTimeout(2500);

                content = page.innerHTML("#app");

                doc = Jsoup.parseBodyFragment(content);
                otherList = getList(content, search, site);
                initList.addAll(otherList);
                // log.info("WE FETCH FROM AFTER PAGE");
                // log.info(Boolean.toString(hasNext));
                rightArrow = doc.getElementsByClass("btn-next").first();
                hasNext = !StrUtil.equals("disabled", rightArrow.attributes().get("disabled"));
            }

        }

        // List<Result> res = getList(site, search);

        log.info("**************BLY FOUND NEW PRODUCTS!!!******************");
        log.info(Integer.toString(initList.size()));
        log.info("**************BLY FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        List<Result> list = new ArrayList<>();

        Document doc = Jsoup.parseBodyFragment(content);

        Element body = doc.getElementsByClass("search-container").get(2);

        Element liCon = body.child(1);

        Element liConInner = liCon.child(0);

        // log.info(liConInner.children().size());
        if (liConInner.children().size() < 3) {
            log.info("BLY FOUND NO RESULTS");
            return list;
        }
        Element liConInner2 = liConInner.child(2);

        Element con = liConInner2.child(0);

        Elements lis = con.getElementsByClass("container");

        for (Element li : lis) {
            // log.info("***************************************************");
            Element nameElement = li.getElementsByClass("info-l").first();
            Element aElement = nameElement.getElementsByTag("p").first();
            String pName = aElement.attributes().get("title");
            Element makerElement = nameElement.getElementsByTag("p").get(1);
            String maker = makerElement.attributes().get("title");

            Element proElement = li.getElementsByClass("info-m").first();

            String propRaw = proElement.child(0).ownText();
            String prop = StrUtil.removePrefix(propRaw, "：");

            Element priceEle = li.getElementsByClass("p1").first();

            String priceClean = priceEle.ownText();

            Double priceDouble = NumberUtil.isNumber(priceClean) ? Double.parseDouble(priceClean) : 0;

            // log.info("商品名是:" + pName);
            // log.info("商品规格是:" + prop);
            // log.info("制造商是:" + maker);
            // log.info("价格是:" + priceClean);
            // log.info("数字价格是:" + priceDouble.toString());

            String productName = StrUtil.concat(true, pName, prop, maker);

            Result re = new Result();
            re.setKeywordStr(search.getKeywordStr());
            re.setMaker(maker);
            re.setProp(prop);
            re.setProductName(productName);
            re.setOrderUrl(site.getSiteUrl());
            re.setScanTime(TimeUtil.currentTime());
            re.setSearchId(search.getId());
            re.setSiteName("佰利源");
            // // // // // re.setSiteId("");
            re.setSiteNo("BLY");
            re.setScanPrice(priceClean);

            re.setPrice(priceDouble);
            re.setStatus(0);

            list.add(re);

            // log.info("PROCESSING BLY SITE FINISH");

        }

        // return "SUCCESS";
        // log.info("FOUND ITEMS:" + Integer.toString(list.size()));

        return list;
    }
}
